package com.person.commons.utils;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang.StringUtils;

public class AuthImage extends HttpServlet {

	private static final long serialVersionUID = 1L;
	private Font mFont = new Font("Times New Roman", Font.PLAIN, 18);

	Color getRandColor(int fc, int bc) {
		Random random = new Random();
		if (fc > 255)
			fc = 255;
		if (bc > 255)
			bc = 255;
		int r = fc + random.nextInt(bc - fc);
		int g = fc + random.nextInt(bc - fc);
		int b = fc + random.nextInt(bc - fc);
		return new Color(r, g, b);
	}

	public void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String imgID = request.getParameter("imgid");
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		response.setContentType("image/jpeg");

		int width = 45, height = 20;
		BufferedImage image = new BufferedImage(width, height,
				BufferedImage.TYPE_INT_RGB);

		Graphics g = image.getGraphics();
		Random random = new Random();
		g.setColor(new Color(108, 124, 242));
		g.fillRect(0, 0, width, height);
		g.setFont(mFont);

		String sRand = "";
		String rand = "";

		for (int i = 0; i < 4; i++) {
			rand = String.valueOf(random.nextInt(10));
			sRand += rand;
			g.setColor(new Color(162, 1, 1));
			g.drawString(rand, 10 * i, 15);
		}

		HttpSession session = request.getSession(true);
		if (StringUtils.isBlank(imgID))
			session.setAttribute(Constants.CHECK_CODE, sRand);
		else
			session.setAttribute(imgID, sRand);
		g.dispose();
		ImageIO.write(image, "JPEG", response.getOutputStream());
	}

}